package com.xbongbong.paas.controller;

import com.alibaba.fastjson.JSON;
import com.xbongbong.paas.service.WebHookService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.BaseVO;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.api.pojo.ApiWebHookRabbitMqDTO;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

/**
 * 钉钉连接器
 * 创建时间 2020/12/28 2:51 PM
 * 修改时间 2020/12/28 2:51 PM
 * @author chy
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/webHook")
public class WebHookController {

    private static final Logger LOG = LoggerFactory.getLogger(WebHookController.class);

    @Resource
    private WebHookService webHookService;

    /**
     * 钉钉触发器
     * @param apiWebHookRabbitMqDTO 关联DTO
     */
    @RequestMapping(value = "/send", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String send(@RequestBody @Valid ApiWebHookRabbitMqDTO apiWebHookRabbitMqDTO, BindingResult br) throws Exception{
        XbbResponse<BaseVO> response = null;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                webHookService.send(apiWebHookRabbitMqDTO);
                response = new XbbResponse<>(new BaseVO());
            } catch (XbbException e) {
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }
}
